<script setup lang="ts">
import request from "@/utils/request";
import { computed, ref, watch } from "vue";
// 城市列表类型
type AreaList = {
  code: string;
  level: number;
  name: string;
  areaList: AreaList[];
};
const cityList = ref<AreaList[]>([]);
const ereaList = ref<AreaList[]>([]);
const getCityList = async () => {
  const res = await request.get(
    "https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json"
  );
  cityList.value = res.data;
  ereaList.value = res.data;
};
getCityList();
const visible = ref(false);
const activeaddress = () => {
  visible.value = true;
};
// 选择城市
const changeResult = ref({
  provinceCode: "",
  provinceName: "",
  cityCode: "",
  cityName: "",
  countyCode: "",
  countyName: "",
});
const select = (item: AreaList) => {
  if (item.level === 0) {
    changeResult.value.provinceName = item.name;
    changeResult.value.provinceCode = item.code;
    cityList.value = item.areaList;
  }
  if (item.level === 1) {
    changeResult.value.cityName = item.name;
    changeResult.value.cityCode = item.code;
    cityList.value = item.areaList;
  }
  if (item.level === 2) {
    changeResult.value.countyName = item.name;
    changeResult.value.countyCode = item.code;
    visible.value = false;
    console.log(changeResult.value);
  }
};
const address = computed(() => {
  return (
    changeResult.value.provinceName +
    changeResult.value.cityName +
    changeResult.value.countyName
  );
});
watch(
  ()=>visible.value,
  ()=>{
    cityList.value=ereaList.value
  }
)
</script>

<template>
  <div class="box">
    <div class="content">
      <span class="" @click="activeaddress">请选择配送地址</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-show="visible">
      <span
        @click="select(item)"
        v-for="item in cityList"
        :key="item.code"
        >{{ item.name }}</span
      >
    </div>
    <div class="address" v-show="!visible"><slot name='title'/>{{ address }}</div>
  </div>
</template>

<style lang="less" scoped>
.box {
  text-align: center;
  height: 50px;
  line-height: 50px;
  background: rgba(255, 255, 255, 0.423);
  .address{
    margin: 0 auto;
  }
  .content {
    width: 20%;
    margin: 0 auto;
    padding: 2px 8px;
    background-color: skyblue;
  }
  .option {
    display: flex;
    flex-wrap: wrap;
    span {
      display: inline;
      margin: 5px 15px;
      cursor: pointer;
    }
  }
}
</style>
